/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}
/**
 * @param {string} path
 * @returns {Boolean}
 */
export function externalParse(path) {
  // open: 默认在当前系统打开相对路径
  if (path.startsWith('open:')) {
    // 待处理来相对路径链接
    return window.location.origin + '/' + path.replace('open:', '')
  }
  return path
}

/**
 * 集成系统链接参数替换
 * @param path
 * @param store
 */
export function urlParamSets(path, store) {  // 匹配格式URL 格式{xxx}，提取出参数名
  const params = path.toString().match(/(?={?)\w+(?=})/g)

  if (typeof params === 'object') {
    for (const i in params) {
      // 参数判断
      const paramValue = store.getters[params[i]]
      if (paramValue) {
        path = path.toString().replace(`{${params[i]}}`, paramValue)
      }
    }
  }
  return path
}
/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUsername(str) {
  const valid_map = ['admin', 'editor']
  return valid_map.indexOf(str.trim()) >= 0
}

export const VDT = {
  messages: {
    email: '请输入有效的电子邮件地址',
    mphone: '请输入正确的手机号格式',
    required: '这是必填字段',
    validatePass2: '校验两次密码'
  },

  email: value => {
    console.log(value)
    if (value !== '' && value !== undefined) {
      return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(
        value
      )
    } else {
      return true
    }
  },
  mphone: function(value) {
    if (value !== '' && value !== undefined) {
      return /^((1[3,5,8,9][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/.test(
        value
      )
    } else {
      return true
    }
  },
  required: (value, param) => {
    return value !== undefined ? value.toString().length > 0 : false
  },
  validatePass2: (value, value2) => {
    console.log(value + '==' + value2)
    return value === value2
  }
}

export const VDATA = (value, config) => {
  for (const fun in config) {
    if (
      typeof VDT[fun] === 'function' &&
      !(config[fun].param === undefined
        ? VDT[fun](value)
        : VDT[fun](value, config[fun].param))
    ) {
      if (typeof config[fun] === 'object') {
        return {
          msg: config[fun].msg ? config[fun].msg : VDT[fun],
          result: false
        }
      } else {
        return {
          msg: typeof config[fun] === 'string' ? config[fun] : VDT[fun],
          result: false
        }
      }
    } else if (typeof config[fun] === 'function') {
      var tmpr = config[fun](value)
      if (tmpr !== '' && tmpr !== undefined && tmpr !== false) {
        return { msg: tmpr, result: false }
      }
    }
  }

  return { msg: '', result: true }
}
